﻿/* BASIC DEF */
var CODE_COUNT = 60;
var BUY = 0;
var SELL = 1;
var HOST = 'http://122.152.199.90:80';
// var HOST = "http://103.251.90.136/";
// var HOST = "";

/* var IMG_PREFIX = HOST + '/file/' */
var AUDIT_PASS = 1;
var AUDIT_FAIL = 2;
var WITHDRAW_FEE = 0.05;

var IMG_PREFIX = 'https://abc-1256878718.cos.ap-shanghai.myqcloud.com/'

var PLATFORM_DATA = {
    jingdong: {
        type: '京东',
        creditType: '白条',
        levels: ['注册会员', '铜牌会员', '银牌会员', '金牌会员', '钻石会员', 'PLUS会员'],
        cko: 'jingdongList',
    },
    taobao: {
        type: '淘宝',
        creditType: '花呗',
        levels: [
            '一星', '二星', '三星', '四星', '五星',
            '一钻', '二钻', '三钻', '四钻', '五钻',
        ],
        cko: 'taobaoList',
    }
}

var AUDIT_STATUS = {
    '-1': '未绑定',
    '0': '待审核',
    '1': '绑定成功',
    '2': '审核不通过',
}

var STATUS_MAP = {
    0: '未支付',
    20: '待审核', // 支付完成后的状态
    30: '任务进行中', // 审核通过，任务进行中
    40: '审核不通过', // 需要重新修改发布
    50: '任务完成',
    60: '任务已过时',
}

var BANKS = ['工商银行', '农业银行', '建设银行', '中国银行', '招商银行', '其他银行']

var PAGE_DATA = {
    pageIndex: 0,
    pageSize: 10,
}

var LOADER = '<div class="mask" id="i-mask" style="position:absolute; top:0; left:0;right:0; bottom:0;z-index:9999999;background:rgba(0,0,0,.05);display:flex;justify-content: center;align-items: center;"><div class="loaded"><div class="loaders "><div class="loader"><div class="loader-inner ball-spin-fade-loader"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div></div></div></div></div>';


/* URL DEF */
var URL_SMS_SEND = '/sms_send';
var URL_EXIT = '/exist';
var URL_UPLOAD_FILE = '/upload';

var URL_SELL_REG = '/shoper/shoper_reg';
var URL_SELL_LOGIN = '/shoper/shoper_login';
var URL_TASK_PUBLISH = '/task/task_publish';
var URL_TASK_CAL_MONEY = '/task/cal_taskmoney';

var URL_TASK_ALL_PLATFORM = '/task/all_platform';
var URL_SELL_SHOPS = '/shoper/shoper_shops/';
var URL_SELL_SHOP_DEL = '/shoper/shop_del/';
var URL_SELL_SHOP_UPDATE = '/shoper/shop_update/';
var URL_SELL_ALL_TASK = '/task/all_tasks/';
var URL_SELL_ALL_RECHARGE = '/shoper/shoper_transfer_list';
var URL_SELL_UPDATE = '/shoper/shoper_update';
var URL_SELL_PASSWD = '/edit_password';
var URL_SELL_PAY_TASK = '/task/prePayForTask?taskId=';
var URL_SELL_BALANCE = '/shoper/shoper_balance';
var URL_SELL_DEL_TASK = '/task/task_del/';
var URL_SELL_ACC_TASK_DETAIL = '/task/task_accept_detail';
var URL_SELL_DELIVERY = '/task/shoper_delivery';
var URL_SELL_ACCEPT_LIST = '/task/task_accept_list';
var URL_SELL_TRANSFER = '/shoper/shoper_transfer';
var URL_SELL_LIST_ORDER = '/tmpl/sell/list_order.tmpl';

var URL_SELL_LIST_TASK = '/task/search_tasks';
var URL_SELL_PAY_ORDER = '/task/approve_buyer_task';
var URL_SELL_TRADE_LIST = '/shoper/shoper_trade_list';
var URL_SELL_EXPORT_TASKS = '/task/export_tasks';

var URL_ADMIN_ALL_SHOP = '/admin/all_shops';
var URL_ADMIN_ALL_TASK = '/admin/all_tasks';
var URL_ADMIN_ALL_IDCARD = '/admin/buyer_list';
var URL_ADMIN_LOGIN = '/admin/admin_login';
var URL_ADMIN_TASK_AUDIT = '/admin/task_approve';
var URL_ADMIN_IDCARD_AUDIT = '/admin/buyer_approve';
var URL_ADMIN_ACOUNT_LIST = '/admin/buyer_acount_list';
var URL_ADMIN_ALL_RECHARGE = '/admin/shoper_transfer_list';
var URL_ADMIN_ACOUNT_AUDIT = '/admin/buyer_acount_approve';
var URL_ADMIN_AUDIT_RECHARGE = '/admin/shoper_transfer_approve';
var URL_ADMIN_SHOP_AUDIT = '/admin/shop_approve';
var URL_SAVE_NOTICE = '/admin/save_notice';
var URL_ADMIN_NOTICE_LIST = '/admin/notice_list';
var URL_ADMIN_NOTICE_DEL = '/admin/notice_del';

var URL_ADMIN_QQ_LIST = '/admin/buyer_qq_list';
var URL_ADMIN_AUDITQQ = '/admin/buyer_qq_approve';

var URL_BUY_NOTICE_LIST = '/notice_list';
var URL_SHOP_BIND = '/shoper/shop_bind';
var URL_BUYER_GET_TASK = '/buyertask/receive_task';
var URL_BUY_REG = '/buyer/buyer_reg';
var URL_BUY_LOGIN = '/buyer/buyer_login';
var URL_BUY_BIND_ID_CARD = '/buyer/buyer_validate';
var URL_BUY_BIND_BANK = '/buyer/buyer_bankbind';
var URL_BUY_BIND_ACCOUNT = '/buyer/buyer_acountbind';
var URL_BUYER_ALL_TASK = '/buyertask/all_tasks';
var URL_BUY_CANCEL_TASK = '/buyertask/cancel_task';
var URL_BUY_WITHDRAW = '/buyer/withdraw_apply';
var URL_BUY_FEE_WITHDRAW = '/buyer/buyer_withdraw_apply';
var URL_BUY_CHECK_SHOP = '/buyertask/check_shop';
var URL_BUY_SUBMIT_ORDER = '/buyertask/task_submit';
var URL_BUY_TASKDETAIL = '/buyertask/taskdetail';
var URL_BUY_BALANCE = '/buyer/buyer_balance';
var URL_BUY_TASK_EVALUATE = '/buyertask/submit_evaluate';
var URL_BUYER_ALL_ORDER = '/buyertask/received_tasks';
var URL_BUY_TRADE_RECORD = '/buyer/buyer_trade_records';
var URL_BUY_INFO = '/buyer/person_info';


var URL_MEMBERSHIP_FEE_TYPE = '/membership_fee_type'; //获取 会员套餐
var URL_MEMBERSHIP_TRANSFER = '/membership_transfer'; //vip充值保存
var URL_MEMBERSHIP_LIST = '/membership_list'; //获取当前用户会员充值记录
var TMPL_VIP_RECHARGE_LIST = '/tmpl/list_vipRecharge.tmpl';

/* MSG DEF */
var MSG_LOGIN_SUCCESS = '登录成功！';
var MSG_REGIS_SUCCESS = '注册成功！';
var MSG_PUBLISH_SUCCESS = '发布成功！';
var MSG_RE_LOGIN = '请重新登录！';
var MSG_BIND_SUCCESS = '提交成功，待审核!';
var MSG_UPDATE_SUCCESS = '修改信息成功';
var MSG_RECHARGE_SUCCESS = '充值成功！';
var MSG_SHOPNAME_CORRECT = '店铺名称正确!';
var MSG_SUBMIT_BUY_CORRECT = '提交购买任务成功！';
var MSG_PUBLISH_FAILED = '发布失败！';
var MSG_DEL_FAILED = '删除失败！';
var MSG_DELIVERY_SUCCESS = '发货成功！';
var MSG_DELIVERY_ERR = '发货出错！';
var MSG_PAY_SUCC = '支付成功！';
var MSG_PAY_ERR = '支付出错！';
var MSG_GET_TASK_DETAIL_ERR = '取买家任务详细信息出错！';
var MSG_BIND_SHOP_SUCC = '绑定商店成功！';
var MSG_CONT_BIND_SHOP = '继续绑定商店';
var MSG_GOTO_SHOP_LIST = '进入店铺管理';
var MSG_GOON_RECHARGE = '继续充值';
var MSG_LOOKUP_RECHARGE = '查看充值记录';
var MSG_ACCEPT_TASK_SUCC = '接单成功！';
var MSG_GOON_ACCEPT = '继续接单';
var MSG_LOOKUP_TASK = '查看任务';
var MSG_UPDATE_FAILED = '更新数据失败！';
var MSG_INPUT_AUDIT_INFO = '请填写审批内容!';
var MSG_WITHDRAW_SUCCESS = '提现成功！';
var MSG_WITHDRAW_FAILED = '提现失败！';
var MSG_TASK_SAVE_SUCC = '任务保存成功！';
var MSG_CONT_CREATE_TASK = '继续创建任务';
var MSG_PUB_TASK = '去发布任务';
var MSG_UPDATE_SHOP_SUCC = '更新店铺数据成功！';
var MSG_CONF_DEL_SHOP = '请确认是否要删除店铺！';
var MSG_CANCEL = '取消';
var MSG_OK = '确定';
var MSG_TASK_PUB_SUCC = '发布任务成功！';
var MSG_WAIT = '等会再说';
var MSG_RECHARGE = '马上充值';
var MSG_TASK_DEL_SUCC = '删除任务成功！';
var MSG_UPLOAD_PIC = '请上传图片！';
var MSG_EVALUATE_SUCC = '提交评价成功！';
var MSG_SELECT_ONE = '请至少选择一个任务';
var MSG_INPUT_KEYWORD = '请输入关键字！';
var MSG_INPUT_TASK_COUNT = '请输入任务数量！';
var MSG_INPUT_KEYWORD_EX = '请输入指定关键词！';
var MSG_INPUT_TEXT = '请输入指定文字！';
var MSG_CONF_DEL_NOTICE = "请确认是否要删除该公告！";

var TEXT_BIND_SUCCESS = '已绑定';
var TEXT_PAY_TASK_INFO = '请于两小时内完成任务，超时平台会自动取消任务并扣取0.5金！若于30分钟内主动撤单，将不会扣取佣金，30分钟后主动撤单，扣取0.2金！';
var TEXT_BROWSER_TASK_INFO = '请于两小时内完成任务，超时平台会自动取消任务并扣取0.2金！若于30分钟内主动撤单，将不会扣取佣金，30分钟后主动撤单，扣取0.1金！';


/* ARRAY & OBJ DEF */

var PAGES = ['login', 'register', 'regs'];

var REGISTER_REGEXS = {
    mobile: /^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/,
    qq: /[1-9][0-9]{4,14}/,
    weixin: /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/,
    password: /\w{6,16}/
};


/* FUNCTION DEF */

function goto(url) {
  if (/(iPhone|iPad|iPod)/i.test(navigator.userAgent)) {
    location.assign(document.location.origin + url)
  } else {
    window.location.href = url;
  }
}

function relogin(info) {
    top.location.href = '/mobile.html';
}

function errorInfo(info) {
    if($('div.alert-dialog').length > 1) return;
    ons.notification.alert(info);
}

function notifyInfo(info) {
    if($('div.alert-dialog').length > 1) return;
    ons.notification.alert(info, {buttonLabels:'确认'});
}

function notifyToast(info) {
    ons.notification.toast(info, {timeout: 400, animation: 'fall'});
}

function addTmpl(tmplUrl) {
    $.ajax({url: tmplUrl, async: false}).then(function(e) { $('body').append(e); });
}

function confirm(msg, cbOk) {
  ons.notification.confirm({
    message: msg,
    buttonLabels: ['取消','确认'],
    callback: function (idx) {
        if(idx === 1) cbOk();
    }
  });
}



/* NAV FUNC DEF */

function navPushPage(url, func) {
    document.getElementById('nav-bar')
        .pushPage(url, { animation : 'slide' } )
        .then(func);
}

function navPopPage(url) {
    document.getElementById('nav-bar')
        .popPage();
}

/* New Ajax DEF */
function promise(method, url, data, cb, err) {
    $("body").append(LOADER);
    var promise = $.ajax({
        type: method,
        url: HOST + url,
        dataType: "json",
        contentType: "application/json",
        data: data,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true
    });
    promise.then(function(e){
        $("#i-mask").remove();
        if (e.code == 0) {
            cb(e.data);
        } else if (e.code == 99) {
            if ((e.message === "")||(e.message === null)) e.message = "系统出错了！"
            errorInfo(e.message);
            if (err !== null) err(e);
        } else if (e.code == -1) {
            relogin();
        }
    })
}


function promiseNoMask(method, url, data, cb, err) {

    var promise = $.ajax({
        type: method,
        url: HOST + url,
        dataType: "json",
        contentType: "application/json",
        data: data,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true
    });
    promise.then(function(e)  {
        if (e.code == 0) {
            cb(e.data);
        } else if (e.code == 99) {
            errorInfo(e.message);
            if (err !== null) err(e);
        } else if (e.code == -1) {
            relogin();
        }
    })
}

function promiseTmpl(method, urlTmpl, urlData, data, cb) {
    $("body").append(LOADER);
    $.when($.ajax(urlTmpl),
        $.ajax({
            type: method,
            url: HOST + urlData,
            dataType: "json",
            contentType: "application/json",
            data: data,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
        })).done(function(tmpl, e) {
        $("#i-mask").remove();
        if (e[0].code == 0) {
            cb(tmpl[0], e[0]);
        } else if (e[0].code == 99) {
            errorInfo(e[0].message);
        } else if (e[0].code == -1) {
            relogin();
        }
    })
}




function promiseTmpl3(method, urlTmpl1, urlTmpl2, url1, url2, cb) {
  $("body").append(LOADER);
  $.when(
    $.ajax(urlTmpl1),
    $.ajax(urlTmpl2),
    $.ajax({
      type: method,
      url: HOST + url1,
      dataType: "json",
      contentType: "application/json",
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
    }),
    $.ajax({
      type: method,
      url: HOST + url2,
      dataType: "json",
      contentType: "application/json",
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
    })
  ).done(function(tmpl1,tmpl2,e1,e2){
    $("#i-mask").remove();
    if ((e1[0].code == 0)&&(e2[0].code==0)) {
      cb(tmpl1[0],tmpl2[0],e1[0],e2[0]);
    } else if ((e1[0].code == 99)||(e2[0].code == 99)) {
      var ERROR = '系统出错了'
      notifyInfo(ERROR);
    } else if ((e1[0].code == -1)||(e2[0].code == -1)) {
      relogin();
    }
  })
}



var promiseObj = function(url, data)  {
    return new Promise(function(resolve, reject){
        $("body").append(LOADER);
        $.ajax({
            type: 'get',
            url: HOST + url,
            dataType: "json",
            contentType: "application/json",
            data: data,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true
        }).done(function(e)  {
            $("#i-mask").remove();
            if (e.code == 0) {
                resolve(e);
            } else if (e.code == 99) {
                notifyInfo(e.message);
            } else if (e.code == -1) {
                relogin();
            }
        })
    })
}

function promiseWhen(method, tmpUrl, firstUrl, secondUrl, data, cb) {
    $("body").append(LOADER);
    $.when($.ajax(tmpUrl),
      $.ajax({
      type: method,
      url: HOST + firstUrl,
      dataType: "json",
      contentType: "application/json",
      data: data,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
    }),
    $.ajax({
      type: method,
      url: HOST + secondUrl,
      dataType: "json",
      contentType: "application/json",
      data: data,
      xhrFields: {
        withCredentials: true
      },
      crossDomain: true,
    })).done(function(tmpl, e1,e2){
      $("#i-mask").remove();
      if (e1[0].code == 0 || e1[0].code == 0) {
        cb(tmpl[0], e1[0], e2[0]);
      } else if (e1[0].code == 99 || e2[0].code == 99) {
        errorInfo(e1[0].message);
      } else if (e1[0].code == -1 || e2[0].code == -1) {
        relogin();
      }
    });
  }


//------------------------------------------------------

function promiseData(method, url, data, cb) {
    $("body").append(LOADER);
    var promise = $.ajax({
        type: method,
        url: HOST + url,
        dataType: "json",
        contentType: "application/json",
        data: data,
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
    });
    promise.done(cb).always(function()  {
        $("#i-mask").remove()
    })
}


var promiseCall = function(url, data) {
    return new Promise(function(resolve, reject) {
        $("body").append(LOADER);
        $.ajax({
            type: 'get',
            url: HOST + url,
            dataType: "json",
            contentType: "application/json",
            data: data,
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true
        }).done(function(ret) {
            resolve(ret)
        }).always(function() {
            $("#i-mask").remove()
        })
    })
}


// TMPL FUNCTION DEF
var rdHelper = {
    formatTime: function(t) {
        return moment(t).format("YYYY-M-D HH:mm:ss")
    },
    div: function(val1, val2) {
        return Number(val1) / Number(val2) * 100
    },
    add: function(val1, val2, val3)  {
        return Number(val1) + Number(val2) + Number(val3)
    },
    formatMoneyType: function(typeId) {
        switch (typeId) {
            case 0:
                ret = '提现本金';
                break;
            case 1:
                ret = '商品预付款';
                break;
            case 2:
                ret = '佣金';
                break;
            case 3:
                ret = '会费';
                break;
            case 4:
                ret = '提款佣金';
                break;
            case 5:
                ret = '存款';
                break;
            case 6:
                ret = '抽佣奖励';
                break;
            case 7:
                ret = '初次任务赏金';
                break;
            case 8:
                ret = '买家超时取消任务罚款';
                break;
            case 9:
                ret = '卖家罚款';
                break;
            case 10:
                ret = '预付资金';
                break;
            case 11:
                ret = '结账';
                break;
            case 12:
                ret = '首单现金奖励';
                break;
            case 13:
                ret = '购买vip奖励';
                break;
        }
        return ret;
    },
    formatOrderStatus: function(s) {
        switch (s) {
            case 0:
                ret = '待处理';
                break;
            case 10:
                ret = '待发货';
                break;
            case 20:
                ret = '待评价';
                break;
            case 30:
                ret = '待审核';
                break;
            case 50:
                ret = '刷手撤销';
                break;
            case 60:
                ret = '系统撤销';
                break;
            case 70:
                ret = '已完成';
                break;
        }
        return ret;
    },
    formatTaskStatus: function(s) {
        switch (s) {
            case 0:
                ret = '未支付';
                break;
            case 20:
                ret = '待审核';
                break;
            case 30:
                ret = '任务进行中';
                break;
            case 40:
                ret = '审核不通过';
                break;
            case 50:
                ret = '任务完成';
                break;
            case 60:
                ret = '任务已过时';
                break;
        }
        return ret;
    },
    formatTaobaoPos: function(s) {
        if (typeof s === 'undefined') return '';
        if (s === '') return '';
        tbArr = ['包邮', '天猫', '球购 ', '消费者保障', '淘金币抵钱', '到付款 ', '7+天退换', '呗分期 ', '天猫超市', '天猫国际', '通用排序'];
        retArr = [];
        s.split(';').forEach(function(v)  {
            retArr.push(tbArr[v])
        })
        return retArr.join('/');
    },
    formatBool: function(s)  {

        return ((parseInt(s) === 1) ? '是' : '否')
    },
    formatSex: function(s) {
        return (((parseInt(s) === 0) || (s === '')) ? '无要求' : s)
    },
    formatAge: function(s)  {
        switch (s) {
            case -1:
            case 0:
                ret = '无要求';
                break;
            case 1:
                ret = '15到25岁';
                break;
            case 2:
                ret = '26到35岁';
                break;
            case 3:
                ret = '36岁以上';
                break;
        }
        return ret;
    },
    formatTaobaoLevel: function(s) {
        switch (s) {
            case 1:
                ret = '1心~2心';
                break;
            case 2:
                ret = '3心~4心';
                break;
            case 3:
                ret = '5心~1钻';
                break;
            case 4:
                ret = '2钻~4钻';
                break;
            case 5:
                ret = '5钻以上';
                break;
            default:
                ret = '无要求';
                break;
        }
        return ret;
    },
    formatRepeat: function(s)  {
        switch (parseInt(s)) {
            case 0:
                ret = '15天不重复';
                break;
            case 1:
                ret = '30天不重复';
                break;
            case 2:
                ret = '60天不重复';
                break;
            case 3:
                ret = '永久不重复';
                break;
            default:
                ret = '无要求';
                break;
        }
        return ret;
    },
    formatExpressStatus: function(s) {
        switch (s) {
            case -1:
                ret = '未发货';
                break;
            case 0:
                ret = '已发';
                break;
            case 1:
                ret = '已收';
                break;
        }
        return ret;
    },
    formatPlatformIcon: function(s) {
        switch (s) {
            case -1:
                ret = '未发货';
                break;
            case 0:
                ret = '已发';
                break;
            case 1:
                ret = '已收';
                break;
        }
        return ret;
    },
    formatNull: function(s)  {
        ret = (s !== "") ? s : "无要求";
        return ret;
    },
    formatEvalReq: function(s, t)  {
        arr = s.split("");
        ret = [];
        arr.forEach(function(v)  {

            if (t === 'pay') {
                switch (parseInt(v)) {
                    case 1:
                        ret.push('普通评价任务');
                        break;
                    case 2:
                        ret.push('关键字好评任务');
                        break;
                    case 3:
                        ret.push('图片好评任务');
                        break;
                    case 4:
                        ret.push('文字好评任务');
                        break;
                }
            } else {
                switch (parseInt(v)) {
                    case 1:
                        ret.push('浏览任务');
                        break;
                    case 2:
                        ret.push('收藏商品');
                        break;
                    case 3:
                        ret.push('关注店铺');
                        break;
                    case 4:
                        ret.push('加购');
                        break;
                }
            }

        })
        return ret.join('/')
    },
    formatShopType: function (s)  {
        if (s === '淘宝') {
            ret = 'taobao.png'
        } else if (s === '京东') {
            ret = 'jingdong.png'
        }
        return ret;
    },
    formatPayMoneyType: function (s)  {
        if (parseInt(s) === 0) {
            ret = '卖家返款'
        } else {
            ret = '买家返款'
        }
        return ret;
    },
    getTaskType:function (s)  {
        if (s.split('')[0] === 'L') {
            ret = 'browse'
        } else {
            ret = 'pay'
        }
        return ret;
    },
    display: function(s, t)  {
        if ((s === 'pay') && (!t)) {
            ret = 'hide'
        }

        if ((s === 'browse') && (!t)) {
            ret = 'hide'
        }

        return ret;
    }
}



// RENDER TMPL FUNCTION
var renderTmpl = function(url, data, help = null)  {
    return new Promise(function(resolve, reject)  {
        $("body").append(LOADER);
        $.ajax(url).done(function(tmpl)  {
            $("#i-mask").remove()
            resolve($.templates(tmpl).render(data, help));
        })
    })
}


function guid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// UPLOAD IMAGE FUNCTION
// var uploadFile = function (target) {
//     return new Promise(function (resolve, reject) {

//         let obj = {
//             key: guid()
//         }
//         promiseNoMask('get', ['/cloudUploadUrl', encodeQuery(obj)].join('?'), null, function(url) {

//             $.ajax({
//                 url: url,
//                 type: 'PUT',
//                 data: target,
//                 async: false,
//                 cache: false,
//                 processData: false,
//                 contentType: false,
//                 success: function (data, file) {
//                     resolve(obj.key);
//                 }
//             })
//         }, null)

//     })
// }


function saveCookie(data) {
    // 先获取 password 和 userType，防止清空
    // data.password ? null : data.password = cookie('password');
    // data.userType || data.userType === 0 ? null : data.userType = cookie('userType');
    data.buyerBankList = [data.buyerBankList[data.buyerBankList.length - 1]];
    Cookies.set('cko', JSON.stringify(data), { expires: 999 });
}

function cookie(id) {
    var obj = JSON.parse(Cookies.get('cko'));
    return (obj!= null)?obj[id]:null;
}

function cookie2(id, pid) {
    var obj = JSON.parse(Cookies.get('cko'));
    return obj[pid][0] ? obj[pid][0][id] : null;
}

function initUserInfo() {
    // var password =  cookie('password');
    // var mobile = cookie('mobile');
    // var obj = { mobile: mobile, password: password };
    // var url = URL_BUY_LOGIN;
    // console.log(JSON.stringify(obj));
    // promiseData('POST', url, JSON.stringify(obj),function (e)  {
    //     e.data.password = password;
    //     console.log(e.data);
    //     saveCookie(e.data);
    // });
    promise('GET', '/buyer/person_info', null, function (e) {
        // console.log(e);
        saveCookie(e);
    }, null);
}

// 获取url中的参数
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}


function encodeQuery(obj) {
    var params = []

    Object.keys(obj).forEach(function(key)  {
        var value = obj[key]
        // 如果值为undefined我们将其置空
        if (typeof value === 'undefined') {
            value = ''
        }
        // 对于需要编码的文本（比如说中文）我们要进行编码
        params.push([key, encodeURIComponent(value)].join('='))
    })

    return params.join('&')
}



function removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
}


function goBack() {
    //解决Safari中后退功能的兼容问题
    if (navigator.userAgent && /(iPhone|iPad|iPod|Safari)/i.test(navigator.userAgent)) {
        window.location.href = window.document.referrer;
    } else {
        window.history.back(-1); //根据需要可使用history.go(-1);
    }
}



function fix(val) {
    return parseFloat(val).toFixed(2)
}


function getTaskType(s) {
    if (s.split('')[0] === 'L') {
        ret = 'browse'
    } else {
        ret = 'pay'
    }
    return ret;
}



function getRootPath(){
    var curWwwPath = window.document.location.href;
    var pathName = window.document.location.pathname;
    var pos = curWwwPath.indexOf(pathName);
    var localhostPath = curWwwPath.substring(0, pos);
    var projectName = pathName.substring(0, pathName.substr(1).indexOf('/')+1);
    return(localhostPath + projectName);
}














!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Compress=e():t.Compress=e()}(this,function(){return function(t){function e(i){if(n[i])return n[i].exports;var a=n[i]={exports:{},id:i,loaded:!1};return t[i].call(a.exports,a,a.exports,e),a.loaded=!0,a.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){var i,a,r;!function(o,u){a=[t,n(1),n(2),n(3),n(4),n(5),n(6)],i=u,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t,e,n,i,a,r,o){"use strict";function u(t){return t&&t.__esModule?t:{default:t}}function s(t){if(Array.isArray(t)){for(var e=0,n=Array(t.length);e<t.length;e++)n[e]=t[e];return n}return Array.from(t)}function f(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}var d=u(e),l=u(n),c=u(i),h=u(a),v=u(r),p=u(o),g=function(){function t(t,e){for(var n=0;n<e.length;n++){var i=e[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,i.key,i)}}return function(e,n,i){return n&&t(e.prototype,n),i&&t(e,i),e}}(),w=function(){function t(){f(this,t)}return g(t,[{key:"attach",value:function(t,e){var n=this;return new Promise(function(i,a){var r=document.querySelector(t);r.setAttribute("accept","image/*"),r.addEventListener("change",function(t){var a=n.compress([].concat(s(t.target.files)),e);i(a)},!1)})}},{key:"compress",value:function(t,e){function n(t,e){var n=new v.default(e);return n.start=window.performance.now(),n.alt=t.name,n.ext=t.type,n.startSize=t.size,p.default.orientation(t).then(function(e){return n.orientation=e,c.default.load(t)}).then(i(n))}function i(t){return function(e){return h.default.load(e).then(function(e){if(t.startWidth=e.naturalWidth,t.startHeight=e.naturalHeight,t.resize){var n=h.default.resize(t.maxWidth,t.maxHeight)(e.naturalWidth,e.naturalHeight),i=n.width,a=n.height;t.endWidth=i,t.endHeight=a}else t.endWidth=e.naturalWidth,t.endHeight=e.naturalHeight;return l.default.imageToCanvas(t.endWidth,t.endHeight,t.orientation)(e)}).then(function(e){return t.iterations=1,t.base64prefix=d.default.prefix(t.ext),a(e,t.startSize,t.quality,t.size,t.minQuality,t.iterations)}).then(function(e){return t.finalSize=d.default.size(e),d.default.data(e)}).then(function(e){t.end=window.performance.now();var n=t.end-t.start;return{data:e,prefix:t.base64prefix,elapsedTimeInSeconds:n/1e3,alt:t.alt,initialSizeInMb:l.default.size(t.startSize).MB,endSizeInMb:l.default.size(t.finalSize).MB,ext:t.ext,quality:t.quality,endWidthInPx:t.endWidth,endHeightInPx:t.endHeight,initialWidthInPx:t.startWidth,initialHeightInPx:t.startHeight,sizeReducedInPercent:(t.startSize-t.finalSize)/t.startSize*100,iterations:t.iterations}})}}function a(t,e){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:1,i=arguments[3],r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:1,o=arguments[5],u=l.default.canvasToBase64(t,n),s=d.default.size(u);return o+=1,s>i?a(t,s,n-.1,i,r,o):n>r?a(t,s,n-.1,i,r,o):n<.5?u:u}return Promise.all(t.map(function(t){return n(t,e)}))}}],[{key:"convertBase64ToFile",value:function(t,e){return l.default.base64ToFile(t,e)}}]),t}();t.exports=w})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=function(t){var e=t.replace(/^data:image\/\w+;base64,/,"").length;return(e-814)/1.37},n=function(t){return t.split(";")[0].match(/jpeg|png|gif/)[0]},i=function(t){return t.replace(/^data:image\/\w+;base64,/,"")},a=function(t){return"data:"+t+";base64,"};t.default={size:e,mime:n,data:i,prefix:a}})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=function(t){for(var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"image/jpeg",n=window.atob(t),i=[],a=0;a<n.length;a++)i[a]=n.charCodeAt(a);return new window.Blob([new Uint8Array(i)],{type:e})},n=function(t,e,n){var i=document.createElement("canvas"),a=i.getContext("2d");return i.width=t,i.height=e,function(r){if(!n||n>8)return a.drawImage(r,0,0,i.width,i.height),i;switch(n>4&&(i.width=e,i.height=t),n){case 2:a.translate(t,0),a.scale(-1,1);break;case 3:a.translate(t,e),a.rotate(Math.PI);break;case 4:a.translate(0,e),a.scale(1,-1);break;case 5:a.rotate(.5*Math.PI),a.scale(1,-1);break;case 6:a.rotate(.5*Math.PI),a.translate(0,-e);break;case 7:a.rotate(.5*Math.PI),a.translate(t,-e),a.scale(-1,1);break;case 8:a.rotate(-.5*Math.PI),a.translate(-t,0)}return n>4?a.drawImage(r,0,0,i.height,i.width):a.drawImage(r,0,0,i.width,i.height),i}},i=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.75,n=t.toDataURL("image/jpeg",e);return n},a=function(t){return{KB:t/1e3,MB:t/1e6}};t.default={base64ToFile:e,imageToCanvas:n,canvasToBase64:i,size:a}})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=function(t){return new Promise(function(e,n){var i=new window.FileReader;i.addEventListener("load",function(t){e(t.target.result)},!1),i.addEventListener("error",function(t){n(t)},!1),i.readAsDataURL(t)})};t.default={load:e}})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=function(t){return new Promise(function(e,n){var i=new window.Image;i.addEventListener("load",function(){e(i)},!1),i.addEventListener("error",function(t){n(t)},!1),i.src=t})},n=function(t,e){return function(n,i){if(!t&&!e)return{width:n,height:i};var a=n/i,r=t/e,o=void 0,u=void 0;return a>r?(o=Math.min(n,t),u=o/a):(u=Math.min(i,e),o=u*a),{width:o,height:u}}};t.default={load:e,resize:n}})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";function e(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var n=function t(n){var i=n.quality,a=void 0===i?.75:i,r=n.size,o=void 0===r?2:r,u=n.maxWidth,s=void 0===u?1920:u,f=n.maxHeight,d=void 0===f?1920:f,l=n.resize,c=void 0===l||l;e(this,t),this.start=window.performance.now(),this.end=null,this.alt=null,this.ext=null,this.startSize=null,this.startWidth=null,this.startHeight=null,this.size=1e3*o*1e3,this.endSize=null,this.endWidth=null,this.endHeight=null,this.iterations=0,this.base64prefix=null,this.quality=a,this.resize=c,this.maxWidth=s,this.maxHeight=d,this.orientation=1};t.default=n})},function(t,e,n){var i,a,r;!function(n,o){a=[e],i=o,r="function"==typeof i?i.apply(e,a):i,!(void 0!==r&&(t.exports=r))}(this,function(t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var e=function(t){return new Promise(function(e,n){var i=new window.FileReader;i.onload=function(t){var n=new DataView(t.target.result);65496!==n.getUint16(0,!1)&&e(-2);for(var i=n.byteLength,a=2;a<i;){var r=n.getUint16(a,!1);if(a+=2,65505===r){1165519206!==n.getUint32(a+=2,!1)&&e(-1);var o=18761===n.getUint16(a+=6,!1);a+=n.getUint32(a+4,o);var u=n.getUint16(a,o);a+=2;for(var s=0;s<u;s++)274===n.getUint16(a+12*s,o)&&e(n.getUint16(a+12*s+8,o))}else{if(65280!==(65280&r))break;a+=n.getUint16(a,!1)}}e(-1)},i.readAsArrayBuffer(t.slice(0,65536))})};t.default={orientation:e}})}])});

// UPLOAD IMAGE FUNCTION
var uploadFile = function(target) {

  return new Promise(function(resolve, reject){
    var compressor = new Compress()
    compressor.compress([target], {
      size: 1,
      quality: .6,
      maxWidth: 1000,
      maxHeight: 1000,
      resize: true
    }).then(function(results)  {
      var output = results[0]
      var compressfile = Compress.convertBase64ToFile(output.data, output.ext)
      var obj = { key: guid() }
      promiseNoMask('get', ['/cloudUploadUrl', encodeQuery(obj)].join('?'), null,  function(url){
        $.ajax({
          url: url,
          type: 'PUT',
          data: compressfile,
          async:false,
          cache: false,
          processData: false,
          contentType: false,
          success: function(data,file){
            resolve(obj.key);
          }
        })
      }, null)

    })//end then

  }) //end return promise
}


function uploadImg(e) {
  var files = e.target.files === undefined ? (e.target && e.target.value ? [{ name: e.target.value.replace(/^.+\\/, '')}] : []) : e.target.files;
  e.stopPropagation();

  if (files.length === 0) {
    return
  }

  var file = files[0]
  uploadFile(file).then(function(data) {
    if (typeof($v)!="undefined") {
      $v.file = data
    }
    $(e.target).attr('picurl', data)
    $(e.target).next().attr('src', IMG_PREFIX + data)
  })
}
